<?php

App::uses('AppController', 'Controller');

/**
 * Orders Controller
 *
 * @property Order $Order
 */
class OrdersController extends AppController {

    function beforeFilter() {
//    $this->Auth->allow('index');
        $this->set('title_for_layout', 'Ordenes de Ruta');
    }

    public function search() {
        $fechaInicio = date("Y-m-d", strtotime($this->request->data('fechaInicio')));
        $fechaFin = date("Y-m-d", strtotime($this->request->data('fechaFin')));

        $this->set('orders', $this->paginate(array('AND' => array('Order.date >=' => $fechaInicio,
                        'Order.date <=' => $fechaFin))));
        $this->layout = 'ajax';
    }

    /**
     * index method
     *
     * @return void
     */
    public function index() {

//        $this->bck();
        $this->Order->recursive = 0;
        if ((!isset($this->request->data['Order']['client_company_id']) && !isset($this->request->data['Order']['company_id']) &&
                !isset($this->request->data['from']) && !isset($this->request->data['to'])) ||
                (empty($this->request->data['Order']['client_company_id']) && empty($this->request->data['Order']['company_id']) &&
                empty($this->request->data['from']) && empty($this->request->data['to']))) {
            $this->paginate = array('order' => 'Order.date desc', 'limit' => 10);
            $this->set('orders', $this->paginate());
        } else {

            $conditions = array();

            if (!empty($this->request->data['Order']['client_company_id'])) {
                $conditions['Order.client_company_id'] = $this->request->data['Order']['client_company_id'];
            }

            if (!empty($this->request->data['Order']['company_id'])) {
                $conditions['Order.company_id'] = $this->request->data['Order']['company_id'];
            }


            $client_company = $this->request->data['Order']['client_company_id'];
            $company = $this->request->data['Order']['company_id'];
            $from = $this->request->data('from');
            $to = $this->request->data('to');

            $this->set(compact('from', 'to', 'company', 'client_company'));

            $fechaInicio = date("Y-m-d", strtotime(trim($this->request->data('from'))));
            $fechaInicio .=' 00:00:00';
            if (empty($this->request->data['to'])) {
                $fechaFin = date('Y-m-d');
            } else {
                $fechaFin = date("Y-m-d", strtotime(trim($this->request->data('to'))));
            }
            $fechaFin .= ' 24:00:00';

            $this->paginate = array('order' => 'Order.date desc');
            $this->set('orders', $this->paginate(array('AND' => array('Order.date >=' => $fechaInicio,
                            'Order.date <=' => $fechaFin,
                            $conditions))
                    ));
            $companies = $this->Order->Company->find('list');
            $clientCompanies = $this->Order->ClientCompany->find('list');
            $this->set(compact('companies', 'clientCompanies'));
        }


        $clientCompanies = $this->Order->ClientCompany->find('list');
        $companies = $this->Order->Company->find('list');
        $this->set(compact('clientCompanies', 'companies'));
    }

    /**
     * ajax index method
     *
     * @return void
     */
    public function bck() {
//        datos locales
//        
        $host = 'localhost';
        $user = 'cacho';
        $pass = 'a123456.';
        $name = 'villa_dispacher';
        
//        Datos del hosting NEOLO
//        $host = 'localhost';
//        $user = 'donburg_villa';
//        $pass = '19.02.1954';
//        $name = 'donburg_villa_dispacher';

//        Inicializo Variables
        $tables = '*';
        $link = mysql_connect($host, $user, $pass);

// Controlamos el error de conexion  
        if (!$link) {
//      Si no conecta a BD,  hacer envio de mail a mi correo avisando
//            die('No puedo conectar, error : ' . mysql_error());
        } else {

            mysql_select_db($name, $link);

// Seleccionamos la BD   

            $return = "";

            //get all of the tables
            if ($tables == '*') {
                $tables = array();
                $result = mysql_query('SHOW TABLES');
                while ($row = mysql_fetch_row($result)) {
                    $tables[] = $row[0];
                }
            } else {
                $tables = is_array($tables) ? $tables : explode(',', $tables);
            }

            //cycle through
            foreach ($tables as $table) {
                $result = mysql_query('SELECT * FROM ' . $table);
                $num_fields = mysql_num_fields($result);

                $return.= 'DROP TABLE ' . $table . ';';
                $row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE ' . $table));
                $return.= "\n\n" . $row2[1] . ";\n\n";
                for ($i = 0; $i < $num_fields; $i++) {
                    while ($row = mysql_fetch_row($result)) {
                        $return.= 'INSERT INTO ' . $table . ' VALUES(';
                        for ($j = 0; $j < $num_fields; $j++) {
                            $row[$j] = addslashes($row[$j]);
                            $row[$j] = ereg_replace("\n", "\\n", $row[$j]);
                            if (isset($row[$j])) {
                                $return.= '"' . $row[$j] . '"';
                            } else {
                                $return.= '""';
                            }
                            if ($j < ($num_fields - 1)) {
                                $return.= ',';
                            }
                        }
                        $return.= ");\n";
                    }
                }
                $return.="\n\n\n";
            }

            // Generate the filename for the sql file
            $file = 'files/bck/dbbackup_' . date("d.m.Y_H:i:s") . '.sql';


            // Save the sql file
            $handle = fopen($file, 'w+');
            fwrite($handle, $return);
            fclose($handle);

            chmod($file, 0777);
            // Close MySQL Connection
            mysql_close();
        }
    }

    /**
     * ajax index method
     *
     * @return void
     */
    public function indexAjax() {
        $this->Order->recursive = 0;
        $this->set('orders', $this->paginate());
        $this->layout = 'ajax';
    }

    /**
     * selectdependiente ajax method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function selectdependiente() {
        $id = $this->request->data('id');

        $drivers = $this->Order->Driver->find('list', array('conditions' => Array('Driver.company_id' => $id)));

        $this->set('drivers', $drivers);

        $vehicles = $this->Order->Vehicle->find('list', array('conditions' => array('Vehicle.company_id' => $id)));
        $this->set('vehicles', $vehicles);

        $coupleds = $this->Order->Coupled->find('list', array('conditions' => array('Coupled.company_id' => $id)));
        $this->set('coupleds', $coupleds);

        $this->layout = 'ajax';
    }

    /**
     * view method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function view($id = null) {
        if (!$this->Order->exists($id)) {
            throw new NotFoundException(__('Invalid order'));
        }
        $options = array('conditions' => array('Order.' . $this->Order->primaryKey => $id));
        $this->set('order', $this->Order->find('first', $options));
        $this->layout = 'impresion';
    }

    public function send($id = null) {
        if ($this->request->is('post')) {

            $id = $this->request->data['Order']['id'];
            $to = $this->request->data['Order']['email'];
            $message = $this->request->data['Order']['message'];

            if (!empty($to)) {
                $fileName = 'files/pdf/ordenes_ruta_pdf.pdf';
                App::uses('CakeEmail', 'Network/Email');


                $email = new CakeEmail('smtp');
                $email->to($to)
                        ->subject('ORDEN DE RUTA');

                //attachment PDF
                $email->attachments(array($fileName));

                //Generating body
                $body = '<p> Orden de Ruta en PDF</p>';

                if (!empty($message)) {
                    $body .= '<p>' . $message . '</p>';
                }

                if ($email->send($body)) {
                    $flashMessage = '<p>El correo fue enviado correctamente.</p>';
                    $this->Session->setFlash($flashMessage);
                    $this->redirect(array('action' => 'send', $id));
                } else {
                    $flashMessage = '<p>El correo no pudo ser enviado. Intentelo nuevamente. </p>';
                    $this->Session->setFlash($flashMessage);
                    $this->redirect(array('action' => 'send', $id));
                }
            } else {
                $flashMessage = '<p>El correo no pudo ser enviado. Intentelo nuevamente. </p>';
                $this->Session->setFlash($flashMessage);
                $this->redirect(array("controller" => "Orders", "action" => "send", $id));
            }
        }

        $options = array('conditions' => array('Order.' . $this->Order->primaryKey => $id));
        $this->set('order', $this->Order->find('first', $options));
    }

    /**
     * add method
     *
     * @return void
     */
    public function add() {

        if ($this->request->is('post')) {
            if (isset($this->request->data['Guardar'])) {
                $this->Order->create();
                if ($this->Order->save($this->request->data)) {
//                    $this->Session->setFlash(__('Orden de Ruta Guardada Exitosamente'));
                    $this->updateTotal($this->request->data['Order']['company_id'], $this->request->data['Order']['total']);
                    $this->updateClientCompany($this->request->data['Order']['client_company_id'], $this->request->data['Order']['total']);
                    $this->redirect(array('action' => 'view', $this->Order->getId()));
                } else {
                    $this->Session->setFlash(__('Orden no Guardada, intente Nuevamente'));
                }
            } else if (isset($this->request->data['Cancelar'])) {

                $this->Session->setFlash(__('Operación Cancelada', true));
                $this->redirect(array('controller' => 'companies', 'action' => 'index'));
            }
        }
        $users = $this->Order->User->find('list', array('conditions' => array('User.role ' => 'empresa')));
        $clientCompanies = $this->Order->ClientCompany->find('list');
        $companies = $this->Order->Company->find('list');
        $drivers = $this->Order->Driver->find('list');
        $products = $this->Order->Product->find('list', array('order' => 'Product.name'));
        $vehicles = $this->Order->Vehicle->find('list');
        $coupleds = $this->Order->Coupled->find('list');


//      Buscamos Choferes para armar select dependiente
        $this->loadModel('Driver');
        $this->Driver->unbindModel(array('hasMany' => array('Order')));
        $this->set('selectDriver', $this->Driver->find('all', array('order' => 'Driver.name')));

//      Buscamos Camiones para armar select dependiente
        $this->loadModel('Vehicle');
        $this->Driver->unbindModel(array('hasMany' => array('Order')));
        $this->set('selectVehicle', $this->Vehicle->find('all', array('order' => 'Vehicle.model')));

//      Buscamos Acoplados para armar select dependiente
        $this->loadModel('Coupled');
        $this->Coupled->unbindModel(array('hasMany' => array('Order')));
        $this->set('selectCoupled', $this->Coupled->find('all', array('order' => 'Coupled.model')));



        $this->set(compact('users', 'clientCompanies', 'companies', 'drivers', 'products', 'vehicles', 'coupleds'));
    }

    /**
     * Ajax add method
     *
     * @return void
     */
    public function addAjax() {
        if ($this->request->is('post')) {
            if (isset($this->request->data['Guardar'])) {
                $this->Order->create();
                if ($this->Order->save($this->request->data)) {
//                    $this->Session->setFlash(__('Orden de Ruta Guardada Exitosamente'));
                    $this->updateTotal($this->request->data['Order']['company_id'], $this->request->data['Order']['total']);
                    $this->redirect(array('action' => 'view', $this->Order->getId()));
                } else {
                    $this->Session->setFlash(__('Orden no Guardada, intente Nuevamente'));
                }
            } else if (isset($this->request->data['Cancelar'])) {

                $this->Session->setFlash(__('Operación Cancelada', true));
                $this->redirect(array('controller' => 'companies', 'action' => 'index'));
            }
        }
        $users = $this->Order->User->find('list', array('conditions' => array('User.role ' => 'empresa')));
        $companies = $this->Order->Company->find('list');
        $drivers = $this->Order->Driver->find('list');
        $products = $this->Order->Product->find('list');
        $vehicles = $this->Order->Vehicle->find('list');
        $coupleds = $this->Order->Coupled->find('list');
    }

    /**
     * edit method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function edit($id = null) {
        $this->Order->id = $id;
        if (!$this->Order->exists($id)) {
            throw new NotFoundException(__('Invalid order'));
        }
        if ($this->request->is('post') || $this->request->is('put')) {

            if (isset($this->request->data['Guardar'])) {

                if ($this->Order->save($this->request->data)) {
                    $this->Session->setFlash(__('Orden de Ruta Guardada Exitosamente'));
                    $this->redirect(array('action' => 'index'));
                } else {
                    $this->Session->setFlash(__('Orden no Guardada, intente Nuevamente.'));
                }
            } else if (isset($this->request->data['Cancelar'])) {

                $this->Session->setFlash(__('Operación Cancelada', true));
                $this->redirect(array('controller' => 'companies', 'action' => 'index'));
            }
        } else {
            $options = array('conditions' => array('Order.' . $this->Order->primaryKey => $id));
            $this->request->data = $this->Order->find('first', $options);
        }
        $users = $this->Order->User->find('list');
        $companies = $this->Order->Company->find('list');
        $drivers = $this->Order->Driver->find('list');
        $products = $this->Order->Product->find('list', array('order' => 'Product.name'));
        $vehicles = $this->Order->Vehicle->find('list');
        $coupleds = $this->Order->Coupled->find('list');

        //      Buscamos Choferes para armar select dependiente
        $this->loadModel('Driver');
        $this->Driver->unbindModel(array('hasMany' => array('Order')));
        $this->set('selectDriver', $this->Driver->find('all', array('order' => 'Driver.name')));

//      Buscamos Camiones para armar select dependiente
        $this->loadModel('Vehicle');
        $this->Driver->unbindModel(array('hasMany' => array('Order')));
        $this->set('selectVehicle', $this->Vehicle->find('all', array('order' => 'Vehicle.model')));

//      Buscamos Acoplados para armar select dependiente
        $this->loadModel('Coupled');
        $this->Coupled->unbindModel(array('hasMany' => array('Order')));
        $this->set('selectCoupled', $this->Coupled->find('all', array('order' => 'Coupled.model')));


        $this->set(compact('users', 'companies', 'drivers', 'products', 'vehicles', 'coupleds'));
    }

    /**
     * delete method
     *
     * @throws NotFoundException
     * @throws MethodNotAllowedException
     * @param string $id
     * @return void
     */
    public function delete($id = null, $total) {

        $order = $this->Order->find('first', array('fields' => array('Order.company_id, Order.client_company_id'), 'conditions' => array('Order.id' => $id)));
        $idCompany = $order['Order']['company_id'];
        $idClientCompany = $order['Order']['client_company_id'];
        $total = $total * -1;

        $this->Order->id = $id;
        if (!$this->Order->exists()) {
            throw new NotFoundException(__('Imposible Borrar, Orden de Ruta Invalida'));
        }
        $this->request->onlyAllow('post', 'delete');
        if ($this->Order->delete()) {
            $this->Session->setFlash(__('Orden de Ruta Borrada'));
            $this->updateClientCompany($idClientCompany, $total);
            $this->updateTotal($idCompany, $total);
            $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('Order was not deleted'));
        $this->redirect(array('action' => 'index'));
    }

    public function updateTotal($idCompany = null, $total = null) {

        $this->loadModel('Company');
        $this->Company->id = $idCompany;
        $saldo = $this->Company->find('first', array('fields' => array('Company.saldo'), 'conditions' => array('Company.id' => $idCompany)));
        $updateTotal = ($saldo['Company']['saldo'] + $total);
        $this->Company->saveField('saldo', $updateTotal);
    }

    public function updateClientCompany($idClientCompany = null, $total = null) {

        $this->loadModel('ClientCompany');
        $this->ClientCompany->id = $idClientCompany;
        $saldo = $this->ClientCompany->find('first', array('fields' => array('ClientCompany.saldo'), 'conditions' => array('ClientCompany.id' => $idClientCompany)));
        $updateTotal = ($saldo['ClientCompany']['saldo'] + $total);
        $this->ClientCompany->saveField('saldo', $updateTotal);
    }

    public function export($from = null, $to = null, $company = null, $client_company = null) {
        App::uses('Folder', 'Utility');
        App::uses('File', 'Utility');

        $name = 'ordenes_ruta_' . date('dmY') . '.csv';

        $csv_file = 'files/csv/' . $name;
        $csv = "";

        if ((!isset($from) && !isset($to) && !isset($company) && !isset($client_company)) ||
                (empty($from) && empty($to) && empty($company) && empty($client_company))) {

            $contacts = $this->Order->find('all');
        } else {


            $conditions = array();

            if ($company !== '*') {
                $conditions['Order.company_id'] = $company;
            }

            if ($client_company !== '*') {
                $conditions['Order.client_company_id'] = $client_company;
            }

            if (($from === '*')) {
                $fechaInicio = '1969-12-31 00:00:00';
            } else {
                $fechaInicio = date("Y-m-d", strtotime(trim($from)));
                $fechaInicio .=' 00:00:00';
            }

            if ($to === '*') {

                $fechaFin = date("Y-m-d");
            } else {

                $fechaFin = date("Y-m-d", strtotime(trim($to)));
            }

            $fechaFin .= ' 24:00:00';

            $contacts = $this->Order->find('all', array(
                'conditions' => array(
                    $conditions,
                    'AND' => array('Order.date >=' => $fechaInicio, 'Order.date <=' => $fechaFin)
                ),
                'order' => 'Order.date desc'
                    ));
        }


        $csv .= "Ordenes de Rutas\n";
        $csv .= "Empresas; Transporte; Chofer; Camion; Acoplado; Origen; Destino; Carga; Fecha\n";
        foreach ($contacts as $key => $contact) {
            $csv .= "{$contact['ClientCompany']['social_razon']};";
            $csv .= "{$contact['Company']['social_razon']};";
            $csv .= "{$contact['Driver']['name']};";
            $csv .= "{$contact['Vehicle']['model']};";
            $csv .= "{$contact['Coupled']['model']};";
            $csv .= "{$contact['Order']['origin']};";
            $csv .= "{$contact['Order']['destination']};";
            $csv .= "{$contact['Product']['name']};";

            $datetime = date('d/m/Y H:i:s', strtotime($contact['Order']['date']));
            $csv .= "{$datetime}\n";
        }

        //Generamos el csv de todos los datos
        $file = new File($csv_file, true, 0777);
        $file->create();
//    if (!$file->open("w")) {
//      $this->Session->setFlash(__('No se puede abrir el archivo'));
//      $this->redirect(array('action' => 'index'));
//    }
        if (!$file->write(utf8_decode($csv))) {
            $this->Session->setFlash(__('No se puede escribir en el archivo'));
            $this->redirect(array('action' => 'index'));
        }
        $file->close();

        chmod('files/csv/' . $name, 0777);
        $this->redirect('/files/csv/' . $name);
    }

    function descargar($id = null) {
        $id = 10;
        if (!$id) {
            $this->Session->setFlash('no has seleccionado ningun pdf.');
            $this->redirect(array('action' => 'index'));
        }
        // Sobrescribimos para que no aparezcan los resultados de debuggin
        // ya que sino daria un error al generar el pdf.
        Configure::write('debug', 2);
        $resultado = $this->Order->find('all');
        $this->set("datos_pdf", $resultado);
        $this->layout = 'pdf'; //esto usara el layout pdf.ctp
        $this->render();
    }

    function pdf() {
        Configure::write('debug', 2);
        $this->layout = 'pdf'; //this will use the pdf.ctp layout
        // Operaciones que deseamos realizar y variables que pasaremos a la vista.
        $this->render();
    }

}
